import { TextModel, SelectionModel, UndoModel } from './models'
import { KeyboardEvent  } from './event'
import { InsertTextOperation, DeleteTextOperation, UndoTextOperation } from './operations'
import { Operation } from './operations/operation'
import { SetSelectionOperation } from './operations/set_selection_operation'
import { ViewProvider } from './view/view_provider'
import { SourceView } from './view'
import isHotkey from 'is-hotkey'
export class Editor {
  container: HTMLElement
  textModel_!: TextModel
  selectionModel_!: SelectionModel
  eventHandler!: KeyboardEvent
  view_!: HTMLElement | SourceView
  undoModel!: UndoModel
  constructor(container: HTMLElement) {
    this.container = container
  }
  init() {
    this.textModel_ = new TextModel()
    this.selectionModel_ = new SelectionModel(this.textModel_)
    this.view_ = new ViewProvider().provide('source_and_preview', this.textModel_, this.selectionModel_, this.container)
    this.eventHandler = new KeyboardEvent(this, this.container, this.view_)
    this.undoModel = new UndoModel()
    this.eventHandler.addListeners()
  }
  apply(operation: Operation) {
    operation.apply(this)
  }
  insertTextAtCursor(text: string) {
    // 获取当前的位置
    const selection = this.selectionModel_.getSelection()
    let startIndex = selection.anchor
    let cursorIndex;
    // 光标的位置
    cursorIndex = startIndex + text.length
    const insertTextOperation = new InsertTextOperation(text, startIndex)
    this.apply(insertTextOperation)
    this.setSelection(cursorIndex, cursorIndex)
  }
  deleteTextCursor() {
    // 先判定当前是否有选取
    // 没选区就只删除前一个字符
    const selection = this.selectionModel_.getSelection()
    let startIndex = selection.anchor
    if (!this.selectionModel_.isCollapsed()) {
      if (this.selectionModel_.isBackkward()) {
        this.apply(new DeleteTextOperation(selection.focus, selection.anchor))
        startIndex = selection.focus
      } else {
        this.apply(new DeleteTextOperation(selection.anchor, selection.focus))
        startIndex = selection.anchor
      }
      
    } else if (selection.anchor > 0) {
      this.apply(new DeleteTextOperation(selection.anchor - 1, selection.focus))
      startIndex--
    }
    this.setSelection(startIndex, startIndex)
  }
  getTextModel() {
    return this.textModel_
  }
  getSelectionModel() {
    return this.selectionModel_
  }
  setSelection(anchor: number, focus: number) {
    const selectionOperaction = new SetSelectionOperation({ anchor, focus })
    this.apply(selectionOperaction)
    console.log(this.getSelectionModel(), 'this.getSelectionModel()')
  }
  undo () {}
  redo () {}
}

export default Editor